﻿using AutoMapper;
using MediatR;
using WarehouseManagement.Application.Command.WarehouseCommand;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;

namespace WarehouseManagement.Application.CommandHandler.WarehouseCommandHandler
{
    // WarehouseCreateCommandHandler 类处理创建仓库的命令
    // 该类实现了 MediatR 的 IRequestHandler 接口，用于处理 WarehouseCreateCommand 命令
    public class WarehouseCreateCommandHandler : IRequestHandler<WarehouseCreateCommand, int>
    {
        private readonly IWarehouseRepository _warehouseRep;
        protected readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="warehouseRepository"></param>
        /// <param name="mapper"></param>
        public WarehouseCreateCommandHandler(IWarehouseRepository warehouseRepository, IMapper mapper)
        {
            this._warehouseRep = warehouseRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 仓库添加
        /// </summary>
        /// <param name="request">要添加的实体</param>
        /// <param name="cancellationToken"></param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> Handle(WarehouseCreateCommand request, CancellationToken cancellationToken)
        {
            // 检查仓库是否存在
            var newAdds = (await _warehouseRep.GetAll()).Where(x => x.WNumber == request.addWarehouseDTO.WNumber).ToList();
            // 如果仓库存在，则返回-1
            if (newAdds.Count > 0)
            {
                return -1;
            }
            else
            {
                // 否则，添加仓库
                return await _warehouseRep.AddAsync(mapper.Map<Warehouse>(request.addWarehouseDTO));
            }

        }
    }
}
